<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['md:project:query']">
      <el-form-item label="财年" prop="year">
        <el-date-picker v-model="queryParams.year" type="year" value-format="yyyy" placeholder="请选择财年"
                        size="small">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" size="small" clearable filterable placeholder="请选择省份"
                   style="width: 100%;">
          <el-option v-for="item in provinceList" :key="item.code" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNo">
        <el-input v-model.trim="queryParams.projectNo" clearable size="small" :max="50"
                  placeholder="请输入项目编号"></el-input>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input v-model.trim="queryParams.name" clearable size="small" :max="50"
                  placeholder="请输入项目名称"></el-input>
      </el-form-item>
      <el-form-item label="客户/代理商" prop="type">
        <el-select v-model="queryParams.type" size="small" clearable filterable placeholder="请选择客户/代理商"
                   style="width: 100%;">
          <el-option v-for="item in projectType" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="clientName">
        <el-input v-model.trim="queryParams.clientName" clearable size="small" :max="50"
                  placeholder="请输入客户"></el-input>
      </el-form-item>
      <el-form-item label="代理商" prop="agentName">
        <el-input v-model.trim="queryParams.agentName" clearable size="small" :max="50"
                  placeholder="请输入代理商"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model.trim="queryParams.contactName" clearable size="small" :max="15"
                  placeholder="请输入联系人"></el-input>
      </el-form-item>
      <el-form-item label="进度" prop="schedule">
        <el-select v-model="queryParams.schedule" size="small" clearable filterable placeholder="请选择进度"
                   style="width: 100%;">
          <el-option v-for="item in dict.type.sys_project_schedule" :key="+item.value" :label="item.label"
                     :value="+item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="进度月份" prop="month">
        <el-date-picker v-model="queryParams.month" type="month" placeholder="请选择进度月份" value-format="yyyy-MM"
                        size="small">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属公司" prop="belongCompany">
        <el-select v-model="queryParams.belongCompany" filterable clearable default-first-option
                   placeholder="请选择所属公司"
                   style="width: 100%">
          <el-option v-for="item in belongCompany" :key="item.id" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model.trim="queryParams.createBy" placeholder="请输入创建人" clearable :maxlength="20" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['md:project:query']"
                   @click="searchHandler">查询
        </el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['md:project:query']"
                   @click="resetHandler">重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:project:add']"
                     @click="openDialog(null)">增加
          </el-button>
          <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:project:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="6">
        <div class="grid-content bg-purple text">
          <span>预算总金额(万元)：{{ allAmount }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content bg-purple text">
          <span>中标总金额(万元)：{{ allBidAmount }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content bg-purple text">
          <span>未开标总金额(万元)：{{ unAmount }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content bg-purple text">
          <span>已终止项目总金额(万元)：{{ stopAmount }}</span>
        </div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" class="cus-el-table" :data="tableData" v-loading="loading" highlight-current-row
              max-height="500"
              v-horizontal-scroll="'auto'" @row-click="handleCurrentChange"
    >
      <el-table-column type="index" width="50" align="center" label="序号" fixed="left">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="projectNo" label="项目编号" align="center" width="140" fixed="left"/>
      <el-table-column property="year" label="财年" align="center" width="80" fixed="left"/>
      <el-table-column property="name" label="项目名称" align="center" min-width="180" fixed="left"/>
      <el-table-column property="belongCompany" label="所属公司" align="center" width="160"/>
      <el-table-column property="amount" label="预算金额(万元)" align="center" width="120"/>
      <el-table-column property="schedule" label="进度" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ getListValue(scope.row.schedule, dict.type.sys_project_schedule) }}</span>
        </template>
      </el-table-column>
      <el-table-column property="nowDate" label="进度日期" align="center" width="100"/>
      <el-table-column property="deliveryDate" label="交付日期" align="center" width="100"/>
      <el-table-column property="guaranteeDate" label="质保日期" align="center" width="100"/>
      <el-table-column property="province" label="省份" align="center" width="100"/>
      <!-- <el-table-column
        property="clientName"
        label="客户"
        align="center"
        width="120"
      /> -->
      <el-table-column label="客户/代理商" align="center" min-width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.clientName && scope.row.clientName.length > 0">
            {{ scope.row.clientName }}
          </span>
          <span v-else>{{ scope.row.agentName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        property="agentName"
        label="代理商"
        align="center"
        width="120"
      /> -->
      <el-table-column property="facultyName" label="二级部门" align="center" width="100"/>
      <el-table-column property="contactName" label="联系人" align="center" width="80"/>
      <el-table-column property="contactJob" label="职务" align="center" width="80"/>
      <el-table-column property="contactPhone" label="手机号码" align="center" width="120"/>
      <el-table-column property="decisionName" label="决策人" align="center" width="80"/>
      <el-table-column property="decisionJob" label="职务" align="center" width="80"/>
      <el-table-column property="decisionPhone" label="手机号码" align="center" width="120"/>
      <el-table-column property="bidAmount" label="中标金额(万元)" align="center" width="120"/>
      <el-table-column property="invoiceAmount" label="累计开票金额(万元)" align="center" width="140"/>
      <el-table-column property="unInvoiceAmount" label="未开票金额(万元)" align="center" width="120"/>
      <el-table-column property="receivedAmount" label="累计收款金额(万元)" align="center" width="140"/>
      <el-table-column property="unReceivedAmount" label="未收款金额(万元)" align="center" width="120"/>
      <el-table-column property="remark" label="备注" align="center" width="80"/>
      <el-table-column property="createBy" label="创建人" align="center" width="80"/>
      <el-table-column property="createTime" label="创建时间" align="center" width="160" sortable/>
      <el-table-column label="操作" align="center"
                       v-if="$auth.hasPermi('md:project:edit') || $auth.hasPermi('md:project:remove') || $auth.hasPermi('md:project:view')">
        <template slot-scope="scope">
          <el-dropdown @command="(val) => handleCommand(val, scope.row)"
                       v-if="$auth.hasPermi('md:project:count:perform')">
            <span class="el-dropdown-link">
              <el-button type="text" icon="el-icon-edit-outline">
                {{ scope.row.isPerformance ? "不参与计算" : "参与计算" }}
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0">参与计算</el-dropdown-item>
              <el-dropdown-item :command="1">不参与计算</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown @command="(val) => handleFileCommand(val, scope.row)"
                       v-if="(scope.row.certification || scope.row.bidCertification || scope.row.checkCertification || scope.row.taskCertification) && $auth.hasPermi('md:project:view')">
            <span class="el-dropdown-link">
              <el-button type="text" icon="el-icon-view">查看附件</el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0" v-if="scope.row.bidCertification">中标文件</el-dropdown-item>
              <el-dropdown-item :command="1" v-if="scope.row.certification">合同文件</el-dropdown-item>
              <el-dropdown-item :command="2" v-if="scope.row.checkCertification">验收单</el-dropdown-item>
              <el-dropdown-item :command="3" v-if="scope.row.taskCertification">任务单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:project:edit']"
                     @click="openDialog(scope.row)">修改
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                         @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['md:project:remove']" type="text"
                       style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <div>
      <el-tabs>
        <el-tab-pane label="详细信息" v-if="$auth.hasPermi('md:project:device:list')">
          <Device v-if="projectInfo.id" :project-info="projectInfo" @change="handleDateUpload"/>
        </el-tab-pane>
        <el-tab-pane label="开票信息" v-if="$auth.hasPermi('md:project:invoice:list')">
          <ProjectInvoice v-if="projectInfo.id" :project-info="projectInfo" @change="handleDateUpload"/>
        </el-tab-pane>
        <el-tab-pane label="回款信息" v-if="$auth.hasPermi('md:project:payment:list')">
          <Payment v-if="projectInfo.id" :project-info="projectInfo" :type="1"/>
        </el-tab-pane>
        <el-tab-pane label="项目进度" v-if="$auth.hasPermi('sa:schedule:list')">
          <Order v-if="projectInfo.id" :project-info="projectInfo" :type="1"/>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
               close-on-click-modal
               :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目来源" prop="type">
              <el-radio-group v-model="form.type" @change="radioChange">
                <el-radio v-for="item in projectType" :key="item.value" :label="item.label">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财年" prop="year">
              <el-date-picker type="year" :disabled="form.schedule >= 8" v-model="form.year" placeholder="选择财年"
                              value-format="yyyy" clearable style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入项目名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算金额" prop="amount">
              <el-input v-model.trim="form.amount" type="number" :min="0" placeholder="请输入预算金额"
                        @input="inputHandler">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.type === '客户'">
          <el-col :span="12">
            <el-form-item label="客户" prop="clientName">
              <el-select v-model="form.clientName" filterable clearable default-first-option placeholder="请选择客户"
                         style="width: 100%" @change="changeCustomerHandler">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级部门" prop="facultyName">
              <el-select v-model="form.facultyName" filterable clearable default-first-option
                         placeholder="请选择二级部门"
                         style="width: 100%" @change="changeSchoolHandler">
                <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.type === '代理商'">
          <el-col :span="12">
            <el-form-item label="代理商" prop="agentId">
              <el-select v-model="form.agentId" filterable clearable default-first-option placeholder="请选择代理商"
                         style="width: 100%" @change="changeAgentHandler">
                <el-option v-for="item in agentList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--            <el-form-item-->
            <!--              label="二级部门"-->
            <!--            >-->
            <!--              <el-input v-model.trim="form.facultyName" :maxlength="100" placeholder="请输入二级部门"/>-->
            <!--            </el-form-item>-->
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactId">
              <el-select v-model="form.contactId" filterable clearable default-first-option placeholder="请选择联系人"
                         style="width: 100%" @change="changeContactHandler">
                <el-option v-for="item in contactList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-checkbox v-model="form.isDecision" @change="checkboxChangeHandler">是否决策人</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="contactJob">
              <el-input v-model.trim="form.contactJob" disabled placeholder="职务"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="contactPhone">
              <el-input v-model.trim="form.contactPhone" disabled placeholder="手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="决策人" prop="decisionId">
              <el-select v-model="form.decisionId" filterable clearable default-first-option placeholder="请选择决策人"
                         style="width: 100%" @change="changeDecisionHandler">
                <el-option v-for="item in contactList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="decisionJob">
              <el-input v-model.trim="form.decisionJob" disabled placeholder="职务"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="decisionPhone">
              <el-input v-model.trim="form.decisionPhone" disabled placeholder="手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进度" prop="schedule">
              <el-select v-model="form.schedule" clearable filterable placeholder="请选择进度" style="width: 100%;">
                <el-option v-for="item in dict.type.sys_project_schedule" :key="+item.value" :label="item.label"
                           :value="+item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进度日期" prop="nowDate">
              <el-date-picker v-model="form.nowDate" type="date" :picker-options="pickerOptions" placeholder="选择日期"
                              value-format="yyyy-MM-dd" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.schedule >= 8 && form.schedule < 100">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model.trim="form.projectNo" placeholder="请输入项目编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中标金额" prop="bidAmount">
              <el-input v-model.trim="form.bidAmount" type="number" :min="0" placeholder="请输入中标金额"
                        @input="inputOtherHandler">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.schedule >= 8 && form.schedule < 100">
          <el-col :span="12">
            <el-form-item label="交付日期" prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择交付日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质保日期" prop="guaranteeDate">
              <el-date-picker v-model="form.guaranteeDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择质保日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.schedule >= 8 && form.schedule < 100">
          <el-col :span="12">
            <el-form-item label="所属公司" prop="belongCompany">
              <el-select v-model="form.belongCompany" filterable clearable default-first-option
                         placeholder="请选择所属公司"
                         style="width: 100%">
                <el-option v-for="item in belongCompany" :key="item.id" :label="item.shortName" :value="item.shortName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <div slot="label" class=" red-dot">合同文件</div>
              <el-upload class="upload-demo" ref="upload" action="#" :limit="1" :on-change="handleChange"
                         :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" accept=".pdf">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件, 且小于2M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="form.schedule >= 6 && form.schedule < 100">
            <el-form-item label="中标文件">
              <el-upload class="upload-demo2" ref="upload2" action="#" :limit="1" :on-change="handleBidChange"
                         :on-remove="handleBidRemove" :file-list="bidFileList" :auto-upload="false" accept=".pdf">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件, 且小于2M</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.schedule >= 9 && form.schedule !== 14 && form.schedule < 100">
            <el-form-item label="验收单">
              <el-upload class="upload-demo3" ref="upload3" action="#" :limit="1" :on-change="handleCheckChange"
                         :on-remove="handleCheckRemove" :file-list="checkFileList" :auto-upload="false" accept=".pdf">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件, 且小于2M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="form.schedule >= 6 && form.schedule < 100">
            <el-form-item label="任务单">
              <el-upload class="upload-demo3" ref="upload3" action="#" :limit="1" :on-change="handleTaskChange"
                         :on-remove="handleTaskRemove" :file-list="taskFileList" :auto-upload="false" accept=".pdf">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件, 且小于2M</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注"
                    :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDataApi,
  checkProjectNameUniqueApi,
  deleteDataApi,
  getDataListApi,
  updateDataApi
} from "@/api/crm/md/project";
import {getDataListApi as getAllCustomerListApi, getCompanyListApi} from "@/api/crm/md/customer";
import {getDataListApi as getAllContactListApi} from "@/api/crm/md/contacts";
import {getDataListApi as getAllSchoolListApi} from "@/api/crm/md/school";
import {getDataListApi as getAllAgentListApi} from "@/api/crm/md/agent";
import {addDataApi as addProjectProcessApi} from "@/api/crm/sa/order"
import {getDataListApi as getFiscalYearListApi} from "@/api/crm/sa/fiscalYear";
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import Device from './components/device.vue';
import Order from './components/order.vue';
import Payment from '@/views/crm/sa/payment/index.vue'
import ProjectInvoice from "@/views/crm/md/project/components/invoice.vue";
import {mapGetters} from 'vuex'
import {isFileOfType} from "@/utils";
import {uploadImgApi} from "@/api/after/serve";

export default {
  name: 'ProjectView',
  components: {ProjectInvoice, Device, Order, Payment},
  dicts: ['sys_key_customer_basis', 'sys_project_schedule'],
  data() {

    const validatebBidAmount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请填写中标金额'));
      } else if (+value > +this.form.amount) {
        callback(new Error('中标金额应小于预算金额'));
      } else {
        callback();
      }
    };

    return {
      stopAmount: 0, // 已终止项目总金额
      env: process.env.VUE_APP_STATIC_API || '',
      uploadLoading: false,
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      unAmount: 0, // 未开标总金额
      currentAmount: 0, // 当前预算金额
      allAmount: 0, // 总预算金额
      currentBidAmount: 0, // 当前中标金额
      allBidAmount: 0, // 当前中标金额 bidAmount
      // 日期选择框设置不能选今日之后的日期
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 项目日期
      projectDate: [],
      // 加载动画
      loading: true,
      // 代理商数据
      agentList: [],
      // 客户数据
      customerList: [],
      // 二级部门数据
      schoolList: [],
      // 联系人数据
      contactList: [],
      // 项目信息
      projectInfo: {
        id: null,
      },
      // 项目来源类型
      projectType: [
        {
          value: "客户",
          label: "客户"
        },
        {
          value: "代理商",
          label: "代理商"
        }
      ],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        taskCertification: "", // 任务单
        bidCertification: "", // 中标文件
        checkCertification: "", // 验收单
        certification: "", // 合同文件
        belongCompany: "", // 博诺集团
        year: "", // 财年
        deliveryDate: "", // 交付日期
        guaranteeDate: "", // 质保日期
        type: "客户", // 项目来源类型
        projectNo: "", // 项目编号
        bidAmount: "", // 中标金额
        agentId: null, // 代理商id
        agentName: "", // 代理商名称
        clientName: "", // 客户名称
        contactId: null, // 联系人id *
        contactJob: "", // 联系人职务
        contactPhone: "", // 联系人手机号
        createTime: "", // 创建时间
        decisionId: null, // 决策人id *
        endDate: "", // 开始时间
        facultyName: "", // 二级部门名称
        nowDate: "", // 项目日期 *
        schedule: 1, // 项目进度 *
        startDate: "", // 开始时间
        updateTime: "", // 更新时间
        isDecision: false, // 是否项目决策人
        address: "", // 地址
        amount: "", // 金额 *
        basis: null, // 重点依据
        decisionJob: "", // 决策人职务
        decisionPhone: "", // 决策人手机号
        createBy: "", // 用户 *
        contactName: "", // 联系人
        id: null, // id
        isImportant: 0, // 是否重点客户 0是普通 1是重点 *
        name: "", // 学校名 *
        province: "", // 省份 *
        remark: "", // 备注
        updateBy: "", // 更新人
        isPerformance: 0, // 0 参与计算销售业绩 1 不参与计算销售业绩
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        certification: [
          {required: true, message: '请上传合同文件', trigger: 'change'}
        ],
        belongCompany: [
          {required: true, message: '请选择博诺集团', trigger: 'change'}
        ],
        deliveryDate: [
          {required: true, message: '请选择交付日期', trigger: 'blur'}
        ],
        guaranteeDate: [
          {required: true, message: '请选择质保日期', trigger: 'blur'}
        ],
        bidAmount: [
          {required: true, validator: validatebBidAmount, trigger: 'blur'}
        ],
        amount: [
          {required: true, message: '请填写预算金额', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请填写名称', trigger: 'blur'}
        ],
        projectNo: [
          {required: true, message: '请填写项目编号', trigger: 'blur'}
        ],
        agentId: [
          {required: true, message: '请选择代理商', trigger: 'change'}
        ],
        clientName: [
          {required: true, message: '请选择客户', trigger: 'change'}
        ],
        facultyName: [
          {required: true, message: '请填写二级部门', trigger: ['change', 'blur']}
        ],
        nowDate: [
          {required: true, message: '请选择日期', trigger: 'blur'}
        ],
        schedule: [
          {required: true, message: '请选择进度', trigger: 'change'}
        ],
        year: [
          {required: true, message: '请选择财年', trigger: 'change'}
        ],
        contactId: [
          {required: true, message: '请选择联系人', trigger: 'change'}
        ],
        decisionId: [
          {required: true, message: '请选择决策人', trigger: 'change'}
        ],
        type: [
          {required: true, message: '请选择项目来源类型', trigger: 'change'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        createBy: "",
        belongCompany: "", // 所属公司
        month: "",
        type: "", // 项目来源的类型
        projectNo: "", // 项目编号
        year: "", // 财年
        name: "", // 项目名称 *
        startDate: "", // 开始时间
        endDate: "", // 开始时间
        contactName: "", // 联系人
        clientName: "", // 客户名称
        agentName: "", // 代理商名称
        schedule: null, // 项目进度 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 财年数据
      fiscalYearList: [],
      belongCompany: [], // 博诺棘集团列表
      fileList: [], // 文件列表
      bidFileList: [], // 中标文件
      checkFileList: [], // 验收单
      taskFileList: [], // 验收单
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    projectDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
    'form.nowDate': {
      handler(newV) {
        if (this.form.schedule === 14) {
          newV && this.fiscalYearCount()
        }
      }
    },
    'form.schedule': {
      handler(newV) {
        if (newV === 14) {
          this.form.nowDate && this.fiscalYearCount()
        }
      }
    },
    tableData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.$refs.tableRef.doLayout()
        })
      }
    },
  },
  mounted() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllCustomerList()
    this.getAllAgentList()
    this.getFiscalYearList()
    this.getCompanyList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 数据需要更新
    handleDateUpload() {
      this.getList()
    },
    // 上传文件
    async uploadImg(fileList, cb = null) {
      if (fileList.length <= 0) {
        cb && cb("")
        return false
      }

      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url)

      if (urlList && urlList[0]) return false

      if (fileList.length <= 0) {
        this.form.certification = ""
        return false
      }

      const file = fileList[0]
      const formData = new FormData()
      formData.append('file', file.raw)
      const {fileName} = await uploadImgApi(formData)

      cb && cb(fileName)

      // this.form.certification = fileName ?? ""
      //
      // if(!this.form.certification) {
      //   this.fileList = []
      // }
    },
    // 查看合同
    handleView(url) {
      window.open(this.env + url)
    },
    // 选中文件
    handleChange(_, fileList) {
      const maxSize = 2; // 限制最大 5MB

      const file = fileList[0] ?? null
      const fileSize = file.size / 1024 / 1024; // 转换为 MB

      if (isFileOfType(file.name, ['.pdf']) && fileSize <= maxSize) {
        this.fileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '请检查文件类型是否为pdf, 且小于2M'
          // message: '文件不符合规范'
        });
        this.fileList = []
      }
    },
    // 选中文件
    handleBidChange(_, fileList) {
      const maxSize = 2; // 限制最大 5MB

      const file = fileList[0] ?? null
      const fileSize = file.size / 1024 / 1024; // 转换为 MB

      if (isFileOfType(file.name, ['.pdf']) && fileSize <= maxSize) {
        this.bidFileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '请检查文件类型是否为pdf, 且小于2M'
          // message: '文件不符合规范'
        });
        this.bidFileList = []
      }
    },
    // 选中文件
    handleCheckChange(_, fileList) {
      const maxSize = 2; // 限制最大 5MB

      const file = fileList[0] ?? null
      const fileSize = file.size / 1024 / 1024; // 转换为 MB

      if (isFileOfType(file.name, ['.pdf']) && fileSize <= maxSize) {
        this.checkFileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '请检查文件类型是否为pdf, 且小于2M'
          // message: '文件不符合规范'
        });
        this.checkFileList = []
      }
    },
    // 选中任务单文件
    handleTaskChange(_, fileList) {
      const maxSize = 2; // 限制最大 5MB

      const file = fileList[0] ?? null
      const fileSize = file.size / 1024 / 1024; // 转换为 MB

      if (isFileOfType(file.name, ['.pdf']) && fileSize <= maxSize) {
        this.taskFileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '请检查文件类型是否为pdf, 且小于2M'
          // message: '文件不符合规范'
        });
        this.taskFileList = []
      }
    },
    // 删除任务单文件
    handleTaskRemove(_, fileList) {
      this.taskFileList = fileList
    },
    // 删除文件
    handleRemove(_, fileList) {
      this.fileList = fileList
    },
    // 删除文件
    handleBidRemove(_, fileList) {
      this.bidFileList = fileList
    },
    // 删除文件
    handleCheckRemove(_, fileList) {
      this.checkFileList = fileList
    },
    // 获取财年数据
    async getFiscalYearList() {
      const res = await getFiscalYearListApi({})
      if (res.code === 200) {
        this.fiscalYearList = res.rows ?? []
      }
    },
    // 计算进度日期属于哪个财年
    fiscalYearCount() {
      const nowDate = this.form.nowDate
      const array = this.fiscalYearList
      for (let i = 0; i < array.length; i++) {
        const element = array[i];
        if (this.isInFiscalYearRange(nowDate, element.startDate, element.endDate)) {
          this.form.year = element.year
          break;
        }
      }
    },
    /**
     * 判断日期是否在指定的财年范围内（支持任意起止日期）
     * @param {string} dateStr - 要检查的日期，格式为 "YYYY-MM-DD"
     * @param {string} startDateStr - 财年开始日期，格式为 "YYYY-MM-DD"
     * @param {string} endDateStr - 财年结束日期，格式为 "YYYY-MM-DD"
     * @returns {boolean} 如果在范围内返回 true，否则返回 false
     */
    isInFiscalYearRange(dateStr, startDateStr, endDateStr) {
      const inputDate = new Date(dateStr);
      const startDate = new Date(startDateStr);
      const endDate = new Date(endDateStr);

      // 判断输入日期是否在范围内（包含边界）
      return inputDate >= startDate && inputDate <= endDate;
    },
    // 产品属性切换
    radioChange() {
      this.form.agentId = null
      this.form.clientName = ""
      this.form.facultyName = ""
      this.form.contactId = null
      this.form.contactJob = ""
      this.form.contactPhone = ""
      this.form.decisionId = null
      this.form.decisionJob = ""
      this.form.decisionPhone = ""
      this.contactList = []
    },
    // 是否项目决策人选择框的回调
    checkboxChangeHandler(val) {
      if (val) {
        this.form.decisionId = this.form.contactId
        this.form.decisionJob = this.form.contactJob
        this.form.decisionPhone = this.form.contactPhone
      }
    },
    // 用户输入的回调
    inputHandler(e) {
      if (+e < 0) this.form.amount = 0
    },
    // 用户输入中标金额的回调
    inputOtherHandler(e) {
      if (+e < 0) this.form.bidAmount = ""
    },
    // 获取全部代理商数据
    getAllAgentList() {
      getAllAgentListApi().then((res) => {
        this.agentList = res.rows ?? []
      })
    },
    // 选中当前列
    handleCurrentChange(row) {
      this.projectInfo = {...row}
    },
    // 改变联系人的回调
    // 根据联系人姓名 在联系人信息表中查询 找到职务、手机号
    changeContactHandler(val) {
      let result = null
      this.contactList.map((item) => {
        if (item.id === val) result = {...item}
      })

      if (result) {
        this.form.contactJob = result.job
        this.form.contactPhone = result.phone
      }
    },
    changeDecisionHandler(val) {
      let result = null
      this.contactList.map((item) => {
        if (item.id === val) result = {...item}
      })

      if (result) {
        this.form.decisionJob = result.job
        this.form.decisionPhone = result.phone
      }
    },
    // 获取全部客户信息
    getAllCustomerList() {
      getAllCustomerListApi().then((res) => {
        this.customerList = res.rows ?? []
        // this.belongCompany = (res.rows ?? []).filter(i => i.clientType === '博诺集团')
      })
    },
    getCompanyList() {
      getCompanyListApi().then((res) => {
        this.belongCompany = (res.rows ?? [])
      })
    },
    // 获取全部二级部门信息
    async getAllSchoolList(clientName) {
      if (!clientName) return false
      const res = await getAllSchoolListApi({clientName})
      this.schoolList = res.rows ?? []
    },
    // 遍历list中的属性per是否与value相同，返回相同的数据项
    isTrueDate(value = "", per = "", list = []) {
      let result = {}
      list.map((item) => {
        if (typeof item[per] === 'number') {
          if (item[per] === value) {
            result = item
          }
        } else {
          if (item[per].localeCompare(value) === 0) {
            result = item
          }
        }
      })

      return result
    },
    // 改变二级部门的回调
    changeSchoolHandler(val) {

      if (!val) return false

      this.cleanContectInfo()

      this.getAllContactList(val)
    },
    // 获取全部联系人信息
    async getAllContactList(val) {
      if (!val) return false
      const flag = this.isTrueDate(val, 'name', this.schoolList)

      const payload = {
        clientAgentId: flag.id,
        // faculty: val,
        type: 0,
      }
      const res = await getAllContactListApi(payload)
      this.contactList = res.rows ?? []
    },
    // 改变客户的回调
    changeCustomerHandler(val) {
      this.form.facultyName = ""
      this.cleanContectInfo()
      this.getAllSchoolList(val)
    },
    // 改变代理商的回调
    changeAgentHandler(val) {
      this.form.facultyName = ""
      this.cleanContectInfo()
      // 获取代理商的信息
      const flag = this.isTrue(val, 'id', this.agentList)
      this.cleanAgentContacts(flag)
    },
    async cleanAgentContacts(val) {
      const res = await getAllContactListApi({
        clientAgentId: val.id,
        type: 1
      })
      if (res.code === 200) {
        this.contactList = res.rows
      }
    },
    // 遍历list中的属性per是否与value相同，返回相同的数据项
    isTrue(value = "", per = "", list = []) {
      let val
      list.map(item => {
        if (item[per] === value) val = item
      })

      return val
    },
    // 清空联系人相关信息
    cleanContectInfo() {
      this.form.contactName = ""
      this.form.contactJob = ""
      this.form.contactPhone = ""
      this.form.decisionJob = ""
      this.form.decisionPhone = ""
      this.form.decisionId = null
      this.form.contactId = null
      this.form.isDecision = false
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if (val === 0) {
        this.form.basis = null
      }
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const { code, data } = await getDataListApi(this.queryParams)
      if (code === 200) {
        this.tableData = data?.list?.rows ?? []
        this.total = data?.list?.total ?? 0

        this.allAmount = data?.totalAmount ?? 0
        this.allBidAmount = data?.totalBidAmount ?? 0
        this.unAmount = data?.unAmount ?? 0
        this.stopAmount = data?.stopAmount ?? 0

        this.currentAmount = this.tableData.reduce((acc, cur) => acc + (cur.amount ?? 0), 0)
        this.currentBidAmount = this.tableData.reduce((acc, cur) => acc + (cur.bidAmount ?? 0), 0)

        // console.log(this.projectInfo)
      }

      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {
          ...row,
          isPerformance: 0,
          isDecision: row.contactId === row.decisionId,
          // oldSchedule: row.schedule,
          year: row.year + "",
        }
        this.getAllSchoolList(this.form.clientName)
        if (row.type === '客户')
          this.getAllContactList(this.form.facultyName)
        else
          this.cleanAgentContacts(this.form.agentName)

        this.fileList = ((row.certification ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: item
        }))
        this.bidFileList = ((row.bidCertification ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: item
        }))
        this.checkFileList = ((row.checkCertification ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: item
        }))
        this.taskFileList = ((row.taskCertification ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: item
        }))
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.schoolList.length = 0
          this.contactList.length = 0
          this.form = {...this.$options.data().form}
        }
        this.fileList = []
        this.bidFileList = []
        this.checkFileList = []
        this.taskFileList = []
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/project/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `projects_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if (this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }

      if (this.form.schedule >= 8 && this.form.schedule < 100 && this.fileList.length <= 0) {
        this.$notify.error({
          title: '错误',
          message: '请上传合同文件'
        });
        return false
      }

      // if (this.form.schedule === 14 && this.taskFileList.length <= 0) {
      //   this.$notify.error({
      //     title: '错误',
      //     message: '请上传任务单'
      //   });
      //   return false
      // }

      this.$refs[formName].validate(async (valid) => {

        if (valid) {
          if (this.form.schedule === 14) {
            this.form.signDate = this.form.nowDate
          }

          try {
            this.uploadLoading = true

            // 上传合同文件
            await this.uploadImg(this.fileList, (fileName) => {
              this.form.certification = fileName ?? ""

              if (!this.form.certification) {
                this.fileList = []
              }
            })

            // 上传中标文件
            await this.uploadImg(this.bidFileList, (fileName) => {
              this.form.bidCertification = fileName ?? ""

              if (!this.form.bidCertification) {
                this.bidFileList = []
              }
            })

            // 上传验收单
            await this.uploadImg(this.checkFileList, (fileName) => {
              this.form.checkCertification = fileName ?? ""

              if (!this.form.checkCertification) {
                this.checkFileList = []
              }
            })

            // 上传任务单
            await this.uploadImg(this.taskFileList, (fileName) => {
              this.form.taskCertification = fileName ?? ""

              if (!this.form.taskCertification) {
                this.taskFileList = []
              }
            })
          } catch (error) {
            this.uploadLoading = false
          }
          this.uploadLoading = false

          if (this.dialogTitle === 1) {
            // 先查询项目是否存在
            this.selProject()
            // this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async selProject() {
      const self = this
      const res = await checkProjectNameUniqueApi(this.form)
      if (res.data) {
        this.$confirm('确定继续增加？', '项目已经存在', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          self.addDataHandler()
        }).catch(() => {
        })
      } else {
        await this.addDataHandler()
      }
    },
    async addProjectProcess(data) {
      const payload = {
        createBy: data.createBy,
        updateBy: data.updateBy,
        nowDate: data.nowDate, // 日期 *
        projectFundId: data.id, // 项目id *
        remark: data.remark, // 备注
        schedule: data.schedule, // 进度 *
        userId: this.user.userId,
      }
      await addProjectProcessApi(payload)
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        // 增加一条项目跟单
        this.addProjectProcess({
          ...payload,
          id: res.data
        })
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        // if (payload.schedule !== payload.oldSchedule) {
        this.addProjectProcess(payload)
        // }
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 数据参与计算销售业绩
    async handleCommand(isPerformance, row) {

      const payload = {
        ...row,
        isPerformance, // 0 参与计算销售业绩 1 不参与计算销售业绩
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        // if(payload.schedule !== payload.oldSchedule) {
        //   this.addProjectProcess(payload)
        // }
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 查看附件 0 中标文件 1 合同文件 2 验收单 3 任务单
    handleFileCommand(isPerformance, row) {
      if (isPerformance === 0) {
        this.handleView(row.bidCertification)
      } else if (isPerformance === 1) {
        this.handleView(row.certification)
      } else if (isPerformance === 2) {
        this.handleView(row.checkCertification)
      } else if (isPerformance === 3) {
        this.handleView(row.taskCertification)
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.projectDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">
.grid-content.text {
  margin-top: 10px;
  color: red;
}

.red-dot::before {
  content: '* ';
  color: red;
}

.cus-el-table {
  width: 100%;
  margin-top: 10px;
}
</style>
